package com.skyolder.milkbee.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.service.WinnerService;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;
import com.skyolder.milkbee.service.dto.WinnerDTO;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing Winner.
 */
@RestController
@RequestMapping("/api")
public class WinnerResource {

    private final Logger log = LoggerFactory.getLogger(WinnerResource.class);
        
    @Inject
    private WinnerService winnerService;

    /**
     * POST  /winners : Create a new winner.
     *
     * @param winnerDTO the winnerDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new winnerDTO, or with status 400 (Bad Request) if the winner has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/winners")
    @Timed
    public ResponseEntity<WinnerDTO> createWinner(@RequestBody WinnerDTO winnerDTO) throws URISyntaxException {
        log.debug("REST request to save Winner : {}", winnerDTO);
        if (winnerDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("winner", "idexists", "A new winner cannot already have an ID")).body(null);
        }
        WinnerDTO result = winnerService.save(winnerDTO);
        return ResponseEntity.created(new URI("/api/winners/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("winner", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /winners : Updates an existing winner.
     *
     * @param winnerDTO the winnerDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated winnerDTO,
     * or with status 400 (Bad Request) if the winnerDTO is not valid,
     * or with status 500 (Internal Server Error) if the winnerDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/winners")
    @Timed
    public ResponseEntity<WinnerDTO> updateWinner(@RequestBody WinnerDTO winnerDTO) throws URISyntaxException {
        log.debug("REST request to update Winner : {}", winnerDTO);
        if (winnerDTO.getId() == null) {
            return createWinner(winnerDTO);
        }
        WinnerDTO result = winnerService.save(winnerDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("winner", winnerDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /winners : get all the winners.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of winners in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/winners")
    @Timed
    public ResponseEntity<List<WinnerDTO>> getAllWinners(@ApiParam Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Winners");
        Page<WinnerDTO> page = winnerService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/winners");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /winners/:id : get the "id" winner.
     *
     * @param id the id of the winnerDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the winnerDTO, or with status 404 (Not Found)
     */
    @GetMapping("/winners/{id}")
    @Timed
    public ResponseEntity<WinnerDTO> getWinner(@PathVariable Long id) {
        log.debug("REST request to get Winner : {}", id);
        WinnerDTO winnerDTO = winnerService.findOne(id);
        return Optional.ofNullable(winnerDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /winners/:id : delete the "id" winner.
     *
     * @param id the id of the winnerDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/winners/{id}")
    @Timed
    public ResponseEntity<Void> deleteWinner(@PathVariable Long id) {
        log.debug("REST request to delete Winner : {}", id);
        winnerService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("winner", id.toString())).build();
    }

}
